package com.sukumar.android.backit.service;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.sukumar.android.backit.R;
import com.sukumar.android.backit.crypto.Cryptoutility;
import com.sukumar.android.backit.mail.Mail;

public class BackItEmailService extends IntentService {

	private Handler handler;

	public BackItEmailService() {
		super("SMSEmailService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle params = intent.getExtras();
		handler = new Handler(Looper.getMainLooper());
		String bingId = params.getString("bingId");
		String action = params.getString("action");

		try {
			backBingAuto(bingId, action);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void backBingAuto(String bingDets, String action) throws Exception {
		SharedPreferences myPrefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		String provider = myPrefs.getString(
				getText(R.string.email_provider_key).toString(), "");
		String userId = myPrefs.getString(getText(R.string.email_address_key)
				.toString(), "");
		String encPass = myPrefs.getString(getText(R.string.email_password_key)
				.toString(), "");
		if (!userId.equals("") && !encPass.equals("")) {
			String password = Cryptoutility.decrypt(encPass);
			Mail m = new Mail(userId, password, provider);
			String[] toArr = { "bingmail-gl@nomura.com" };
			m.set_to(toArr);
			m.set_from(userId);
			m.set_subject(action + " " + bingDets);
			m.set_body("");
			if (m.send()) {
				handler.post(new Runnable() {
					public void run() {
						Toast.makeText(getApplicationContext(),
								"Email was sent successfully.",
								Toast.LENGTH_LONG).show();
					}
				});
			} else {
				handler.post(new Runnable() {
					public void run() {
						Toast.makeText(getApplicationContext(),
								"Email was not sent.", Toast.LENGTH_LONG)
								.show();
					}
				});
			}
		} else {
			handler.post(new Runnable() {
				public void run() {
					Toast.makeText(
							getApplicationContext(),
							"Please enter your e-mail credentials in preferences",
							Toast.LENGTH_LONG).show();
				}
			});
		}
	}
}
